package mt.server;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import mt.Order;
import mt.comm.ServerComm;
import mt.comm.ServerSideMessage;

public class RunnableServer implements Runnable {

	private ServerComm serverComm;
	private HashMap<Integer, Order> SellOrders;
	private HashMap<Integer, Order> buyOrders;
	private static int totalOrderNumber = 0;
	private Set<String> clients;

	public RunnableServer(ServerComm serverComm) {
		// TODO Auto-generated constructor stub
		this.serverComm = serverComm;
		this.SellOrders = new HashMap<Integer, Order>();
		this.buyOrders = new HashMap<Integer, Order>();
		this.clients = new HashSet<String>();
	}

	@Override
	public void run() {
		while(true){
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO A//e.printStackTrace();
			}
		if (serverComm.hasNextMessage()) {
			ServerSideMessage newMessage = serverComm.getNextMessage();
			processReceivedMessage(newMessage);
		}
		}
	}

	private void processReceivedMessage(ServerSideMessage newMessage) {
		if ( (newMessage != null) && (newMessage.getType().equals(ServerSideMessage.Type.NEW_ORDER)) ){
			// processar a mensagem
			Order currentOrder = newMessage.getOrder();
			boolean updatedOrder = updateOrder(currentOrder);
			//matchOrders
//			matchOrders(currentOrder);
//			updateClients();
		}
		System.out.println(newMessage.toString());

	}

	private boolean updateOrder(Order currentOrder) {
		//codigo adicionado
		/*if (totalOrderNumber == 0){
			++totalOrderNumber;
			//System.out.println(currentOrder.toString());
			
			currentOrder.setServerOrderID(1);
			addClient(currentOrder.getNickname());
			
			return false;
		}*/
		//codigo adicionado
		
		//else
			if (currentOrder.getServerOrderID() == 0) {//recebemos nova ordem
			++totalOrderNumber;
			currentOrder.setServerOrderID(totalOrderNumber);
			addClient(currentOrder.getNickname());
			return false;
		} else {
			if (currentOrder.isBuyOrder()) {//update order
				this.buyOrders.put(currentOrder.getServerOrderID(),
						currentOrder);
			}
			return true;
		}

	}
	private void checkConections(){


		/*desconectar

		* remover o cliente do hashset

		* remover as orders*/


		for(String client:this.clients){

			if(!serverComm.clientIsConnected(client)){

				serverComm.disconnectClient(client);

				Iterator<Order> selIt = SellOrders.values().iterator();

				while (selIt.hasNext()){

					Order order = selIt.next();

					if (order.getNickname().compareTo(client)==0){

						SellOrders.remove(order.getServerOrderID());

					}

				}

				Iterator<Order> buyIt = buyOrders.values().iterator();

				while(buyIt.hasNext()){

					Order order = buyIt.next();

					if(order.getNickname().compareTo(client)==0){

						buyOrders.remove(order.getServerOrderID());

						}
					}
				}
			}

		}

	private void addClient(String nickname) {
		// TODO Auto-generated method stub
		if (nickname != null)
			this.clients.add(nickname);
	}
}
